package de.hsowl.tod4a.client;

import java.io.IOException;

import de.hsowl.tod4a.client.http.HttpClient;
import de.hsowl.tod4a.global.exception.ObjectServerRemoteException;
import de.hsowl.tod4a.global.http.HttpResponse;
import de.hsowl.tod4a.global.model.ClientProperty;

public class ObjectClient {

	private HttpClient socket;
	public final static int VERSION = 1;

	public ObjectClient(String url, int port, String username, String password, ClientProperty props) throws IOException {

		// Sockets im main Thread erlauben
		if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) {
			android.os.StrictMode.ThreadPolicy policy = new android.os.StrictMode.ThreadPolicy.Builder().permitAll().build();
			android.os.StrictMode.setThreadPolicy(policy);
		}

		socket = new HttpClient(url,port, 2000, username, password,props);
	}

	/**
	 * See {@link EntityManager}
	 * 
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public String getByClass(String xml) throws Exception {
		HttpResponse resp = socket.send(xml);
		if (resp.STATUS.equals(HttpResponse.STATUS_OK)) {
			return resp.CONTENT;
		} else {
			throw new ObjectServerRemoteException(resp.CONTENT);
		}
	}

	/**
	 * See {@link EntityManager#addUser(String, String)}
	 * 
	 * @param xml
	 * @throws IOException
	 */
	public void addUser(String xml) throws IOException {
		send(xml);
	}

	/**
	 * Sends a message to a server
	 * 
	 * @param xml
	 * @throws IOException
	 */
	private void send(String xml) throws IOException {
		HttpResponse resp = socket.send(xml);
		if (resp.STATUS.equals(HttpResponse.STATUS_BAD)) {
			throw new ObjectServerRemoteException(resp.CONTENT);
		}
	}

	/**
	 * See {@link EntityManager#removeUser(String)}
	 * 
	 * @param xmlMessage
	 * @throws Exception
	 */
	public void removeUser(String xmlMessage) throws Exception {
		send(xmlMessage);
	}

	/**
	 * See {@link EntityManager#store(Object...)}
	 * 
	 * @param xml
	 * @throws Exception
	 */
	public void store(String xml) throws Exception {
		send(xml);
	}

	/**
	 * See {@link EntityManager#close()}
	 */
	public void close() {
		if (socket != null && socket.isConnected()) {
			socket.close();
		}
	}

	/**
	 * See {@link EntityManager#remove(Object...)}
	 * 
	 * @param xml
	 * @throws IOException
	 */
	public void remove(String xml) throws IOException {
		send(xml);
	}

}
